const http = require('http');
const fs = require('fs');
const { URL } = require('url');

const json = [
  {
      "name": "太阳能电池板.gif",
      "type": "file",
      "mtime": "Mon, 05 Feb 2024 07:30:30 GMT",
      "size": 147018
  },
  {
      "name": "太阳能电池板.svg",
      "type": "file",
      "mtime": "Mon, 05 Feb 2024 07:30:30 GMT",
      "size": 35536
  },
  {
      "name": "汇流箱.svg",
      "type": "file",
      "mtime": "Mon, 05 Feb 2024 07:30:30 GMT",
      "size": 13883
  },
  {
      "name": "电网.svg",
      "type": "file",
      "mtime": "Mon, 05 Feb 2024 07:30:30 GMT",
      "size": 62887
  },
  {
      "name": "箱式变压.svg",
      "type": "file",
      "mtime": "Mon, 05 Feb 2024 07:30:30 GMT",
      "size": 8731
  },
  {
      "name": "逆变器.svg",
      "type": "file",
      "mtime": "Mon, 05 Feb 2024 07:30:30 GMT",
      "size": 28509
  },
  {
      "name": "配电柜.svg",
      "type": "file",
      "mtime": "Mon, 05 Feb 2024 07:30:30 GMT",
      "size": 26148
  }
];

const urlPrefix = "http://assets.le5lecdn.com/png/2.5D-光伏系统/";

json.forEach(item => {
  const downloadUrl = urlPrefix + encodeURIComponent(item.name);
  const urlObj = new URL(downloadUrl);

  const options = {
    hostname: urlObj.hostname,
    port: 80,
    path: urlObj.pathname + urlObj.search,
    method: 'GET',
    headers: {
      'Content-Type': 'image/svg+xml'
    }
  };

  const req = http.request(options, (res) => {
    const fileName = item.name;
    const fileStream = fs.createWriteStream(fileName);

    res.pipe(fileStream);

    fileStream.on('finish', () => {
      fileStream.close();
      console.log(`${fileName} 下载完成`);
    });
  });

  req.on('error', (error) => {
    console.error(`请求失败: ${error.message}`);
  });

  req.end();
});
